/*************************************************************
 * File: MenuResource.java
 * Copyright (c) 2012
 * Author: Huang Shaobin
 * Email: Shaobin.Software@gmail.com Shaobin_Software@163.com 
 * Date: Feb 15, 2013
 * Description: 
 ************************************************************/

package snow.biz.system.web.resource;

import java.util.Arrays;

import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;

import snow.biz.base.model.BaseEntity;
import snow.biz.security.model.Resource;
import snow.biz.security.service.IResourceService;
import snow.biz.system.web.SystemWebConstants;
import snow.core.enums.Status;
import snow.core.persistence.query.AndedConditions;
import snow.core.persistence.query.BinaryOperator;
import snow.core.persistence.query.Condition;
import snow.core.persistence.query.Order;
import snow.core.security.Operation;
import snow.core.security.OperationType;
import snow.core.web.restlet.ResourceSupport;

/**
 * 菜单管理
 * 
 * @author Shaobin.Software@gmail.com Shaobin_Software@163.com
 * @version 1.0
 */
@Path(SystemWebConstants.PATH_MENUS)
@snow.core.security.Resource(uri = SystemWebConstants.RESOURCE_MENUS, name = "菜单管理", desc = "菜单管理")
public class MenuResource extends ResourceSupport {

	private IResourceService resourceService;

	public IResourceService getResourceService() {
		return this.resourceService;
	}

	@GET
	@Operation(OperationType.SEARCH)
	@Produces(MediaType.APPLICATION_JSON)
	public Object listMenus(@QueryParam("parentId")
	@DefaultValue("-1")
	String parentIdVal) {
		AndedConditions conditions = new AndedConditions();
		conditions.addCondition(new Condition("asMenu", BinaryOperator.EQ, Boolean.TRUE));
		conditions.addCondition(new Condition("status", BinaryOperator.EQ, Status.SUCCESS));
		final int parentId = NumberUtils.toInt(parentIdVal, -1);
		if (parentId > 0) {
			Resource parent = resourceService.searchResourceFrom(Integer.valueOf(parentId));
			if (BaseEntity.validEntity(parent)) {
				conditions.addCondition(new Condition("uri", BinaryOperator.LIKE, StringUtils.trim(parent.getUri()) + "%"));
				conditions.addCondition(new Condition("id", BinaryOperator.NE, parent.getId()));
			}
		} else {
			conditions.addCondition(new Condition("asRoot", BinaryOperator.EQ, Boolean.TRUE));
		}
		return resourceService.searchResourcesFrom(conditions, Arrays.asList(new Order[] { Order.desc("sort"), Order.desc("id") }), -1, -1);
	}

	public void setResourceService(IResourceService resourceService) {
		this.resourceService = resourceService;
	}

}
